/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package e.z.blog.back.com.impl.dao;

import e.z.blog.back.com.DaoTabApi;
import e.z.blog.back.bean.State;
import e.z.blog.back.bean.base.Tab;
import java.util.List;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

/**
 *
 * @author EnzoZhong
 */
@IocBean
public class DaoTab implements DaoTabApi {

        @Inject( "refer:$Ioc" )
        private Ioc ioc;
        @Inject
        private Dao dao;

        @Override
        public Tab create ( Tab tab ) {
                tab.setState( State.YELLOW );
                return dao.insert( tab );
        }

        @Override
        public List<Tab> readAll () {
                return dao.query( Tab.class , null , null );
        }

        @Override
        public Tab read ( Tab tab ) {
                Integer tabId = tab.getTabId();
                String tabName = tab.getTabName();
                Cnd cnd = Cnd.where( "tabId" , "=" , tabId ).or( "tabName" , "=" , tabName );
                return dao.fetch( Tab.class , cnd );
        }

        @Override
        public Tab update ( Tab tab ) {
                Tab defCity = ioc.get( Tab.class , "defTab" );
                //判断是否缺省城市，如果是不做任何修改。
                if ( tab.getTabName().equalsIgnoreCase( defCity.getTabName() ) ) {
                        /**
                         * do nothing
                         */
                } else {
                        dao.update( tab );
                }
                return tab;
        }

        @Override
        public Tab delete ( Tab type ) {
                type = read( type );
                Tab defTab = ioc.get( Tab.class , "defTab" );
                if ( defTab.getTabName().equalsIgnoreCase( type.getTabName() ) ) {
                        /*
                         * do nothing~
                         */
                } else {
                        switch ( type.getState() ) {
                                case State.BLACK: {
                                        dao.delete( type );
                                        break;
                                }
                                default: {
                                        type.setState( type.getState() + 1 );
                                        dao.update( type );
                                        break;
                                }
                        }
                }
                return type;
        }
}
